package com.my.netty.basic.echoserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

@Slf4j
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) {
                        sc.pipeline().addLast(new StringEncoder());
                        sc.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("服务端回声：{}", buf.toString(Charset.defaultCharset()));
                                //这个ByteBuf不用释放，往下传到tail会被自动释放
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();
        log.info("已连接连接服务端 {}", channel);
        Scanner sc = new Scanner(System.in);
        String line;
        while (true) {
            System.out.println("输入向服务端发送的数据：");
            line = sc.nextLine();
            if ("q".equalsIgnoreCase(line)) {
                break;
            }
            channel.writeAndFlush(line);
        }
        sc.close();

        channel.close();
        channel.closeFuture().addListener((ChannelFutureListener) future -> {
            log.info("客户端退出");
            eventLoopGroup.shutdownGracefully();
        });
    }
}
